package action;

import config.ApplicationConfig;
import server.HistoryServer;
import server.LogoutServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;

/**
 * User: tum0r
 * Package Name: ${PACKAGE_NAME}
 * Time: 2019-03-10 Sunday 21:26:09
 */
public class LogoutServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        LinkedHashMap<String, String> pageConfig = ApplicationConfig.readConfig("page.json");
        request.setCharacterEncoding(pageConfig.get("encode"));
        response.setCharacterEncoding(pageConfig.get("encode"));

        HttpSession session = request.getSession();
        session.setAttribute("infoTitle", "用户退出");
        session.setAttribute("panelColor", "blue");
        session.setAttribute("return", "index.jsp");
        String username = request.getParameter("username");
        LogoutServer logoutServer = new LogoutServer();
        logoutServer.open();
        LinkedList<LinkedHashMap<String, Object>> temp = logoutServer.getUserInfo(username);
        boolean flag = logoutServer.logout(username);
        if(flag){
            session.setAttribute("infoContent", "退出成功");
            session.setAttribute("cookie", "");
            session.setAttribute("user", "");
        }else{
            session.setAttribute("panelColor", "red");
            session.setAttribute("infoContent", "退出失败");
        }
        logoutServer.close();

        if(temp.size()!=0){
            HistoryServer historyServer = new HistoryServer();
            historyServer.open();
            historyServer.record(temp.get(0).get("user_id").toString(), username + "尝试退出，退出" + (flag?"成功":"失败"), request);
            historyServer.close();
        }
        response.sendRedirect("information.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
